/*
使用提示：
1.请给它足够的耐心，等它暖好机    2.确认线插稳了  3.用的时间久了就是会有问题，让它休息一下吧    4.如果没反应就挪一
下它的位置，至于为什么有时这样做就会变得正常，大概还是接触不良    5.它本身用的xh254端子好像就不适合杜邦线去连，尽量
用转接头，稳妥一点。  6.不要犯什么明明触发了回调却没在其中用串口助手打印导致以为是没有反应的不可理喻的错误
绝赞持续更新中……
*/
#include "../../../../include/driver/pinctrl.h"
#include "../../../../kernel/osal/include/soc_osal.h"
#include "../../../../include/driver/uart.h"
#include "../../../../include/driver/watchdog.h"
#include "../../../../kernel/osal/include/debug/osal_debug.h"
#include "../../../../kernel/liteos/liteos_v208.5.0/Huawei_LiteOS/open_source/CMSIS/CMSIS/RTOS2/Include/cmsis_os2.h"
#include "../../../../middleware/utils/app_init/app_init.h"

#include "CO2.h"
#include "main.h"

uint8_t g_app_uart_rx_buff[UART_TRANSFER_SIZE] = {0};
uint32_t co2 = 0;

/*
本项目中用到的JW01模块是每隔一秒自动发送一次数据的那种型号，错过了就没有了。除非把读取之间的延时降得很低，否则总会有
没读到的情况。因此可以使用中断模式，缓冲区收满了就进中断，进行处理就很方便。
*/
void uart_rx_callback(const void *buffer, uint16_t length, bool error)
{
    if (error)
        osal_printk("CO2 read data error happend");
    else
    {
        uint8_t sum = 0;
        for (uint8_t i = 0; i < UART_TRANSFER_SIZE - 1; i++)
        {
            sum += ((uint8_t*)buffer)[i];
        }
        if (sum == ((uint8_t*)buffer)[UART_TRANSFER_SIZE - 1])
        {
            sle_tx_buff[CO2 - 3 + 2] = ((uint8_t*)buffer)[1];
            sle_tx_buff[CO2 - 3 + 3] = ((uint8_t*)buffer)[2];
            co2 = ((uint8_t*)buffer)[1] * 256 + ((uint8_t*)buffer)[2];
            osal_printk("CO_2:%dppm\n", co2);
        }
        else
        {
            osal_printk("CO2 read data error happend");
        }
    }
}

void pin_init(void)
{
    uapi_pin_set_mode(CONFIG_UART_TXD_PIN, PIN_MODE_2);//引脚模式设置为2
    uapi_pin_set_mode(CONFIG_UART_RXD_PIN, PIN_MODE_2);
}

uart_buffer_config_t g_app_uart_buffer_config = {
    .rx_buffer = g_app_uart_rx_buff,
    .rx_buffer_size = UART_TRANSFER_SIZE
};

void uart_config(void)
{
    uart_attr_t attr = {
        .baud_rate = UART_BAUDRATE,
        .data_bits = UART_DATA_BITS,
        .stop_bits = UART_STOP_BITS,
        .parity = UART_PARITY_BIT
    };
    uart_pin_config_t pin_config = {
        .tx_pin = CONFIG_UART_TXD_PIN,
        .rx_pin = CONFIG_UART_RXD_PIN,
        .cts_pin = PIN_NONE,
        .rts_pin = PIN_NONE
    };
    uapi_uart_deinit(CONFIG_UART_BUS_ID); 
    uapi_uart_init(CONFIG_UART_BUS_ID, &pin_config, &attr, NULL, &g_app_uart_buffer_config);
}

void CO2_init(void)
{
    pin_init();
    uart_config();
    uart_rx_condition_t uart_rx_condition = UART_RX_CONDITION_FULL_OR_SUFFICIENT_DATA_OR_IDLE;
    uapi_uart_register_rx_callback(CONFIG_UART_BUS_ID, uart_rx_condition,
                    sizeof(uint8_t) * UART_TRANSFER_SIZE, uart_rx_callback);
    osal_printk("CO2 init succ\r\n");
}
